import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import pageMW from "../../middleware/pager";
import {
  getActivityOfStore,
  createActivityOfStore,
  updateActivityOfStore,
  checkActivityOfStoreParamFields,
  pauseActivityOfStore,
  resumeActivityOfStore,
  publishActivityOfStore,
  listActivityItemOfStoreWithStatsByStoreID,
} from "../../service/activityService";
import {
  AggsToActivityUserPvCount,
  listAggsToActivityUserPvCounts,
} from "../../service/activityUserPvLogService";
import { _pick, reduceToObject, isUndefined } from "mmb";
import { UpdateActivityOfStoreParams } from "../../service/declareTypes";
import ActivitySaleMode from "../../bg-enums/activitySaleMode";
import ActivityProcessStatus, {
  isActivityProcessStatus,
} from "../../bg-enums/activityProcessStatus";

const router = createStoreApiMWRouter();

// 获取门店的活动列表(门店管理视角)
router.get("/sto/:storeId/activities", pageMW, async (ctx: AppCTX, next) => {
  const { storeId } = ctx.params;
  let { isAll, processStatus, keyword } = ctx.query;
  const { userId, limit, offset, ts } = ctx;
  let arrProcessStatus: ActivityProcessStatus[] = [];
  if (!isUndefined(processStatus)) {
    for (let ps of processStatus.split(",")) {
      if (!isActivityProcessStatus(ps)) {
        ctx.throw(400, "processStatus invalid");
      }
      arrProcessStatus.push(ps);
    }
  }
  const { total, items } = await listActivityItemOfStoreWithStatsByStoreID(
    {
      storeId,
      isAll: isAll === "true",
      processStatuses: arrProcessStatus,
      keyword,
    },
    {
      limit,
      offset,
      ts,
    }
  );

  ctx.body = {
    total,
    rows: items,
  };
});

// 获取门店活动详情(门店管理视角)
router.get("/sto/:storeId/activity/:activityId", async (ctx: AppCTX, next) => {
  const { storeId, activityId } = ctx.params;
  const { userId } = ctx;

  const activity = await getActivityOfStore(activityId, storeId);
  if (activity.storeId !== storeId) {
    ctx.throw(400, "no belong current brand");
  }

  ctx.body = {
    ...activity,
  };
});

// 新增门店活动
router.post("/sto/:storeId/activity", async (ctx: AppCTX, next) => {
  const { storeId } = ctx.params;
  const { userId } = ctx;
  const {
    type,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    saleMode,
    minimumPurchaseAmount,
    tel,
    // productWithSkus
    activityProductWithSkus,
    // consignment
  } = ctx.request.body;
  let { consignment, maxiumPurchaseFrequency } = ctx.request.body;

  if (saleMode === ActivitySaleMode.ONLY_STORE_SELLING) {
    consignment = {
      allowHiddenProduct: false,
      allowAllSpokesman: false,
      consignmentBonusSettings: [],
      specificSpokesmanIds: [],
    };
  }

  // check params
  checkActivityOfStoreParamFields({
    type,
    intro,
    begined,
    ended,
    timeRanges,
    saleMode,
    maxiumPurchaseFrequency,
    activityProductWithSkus,
    consignment,
  });
  if (maxiumPurchaseFrequency === 0) {
    maxiumPurchaseFrequency = undefined;
  }

  const activity = await createActivityOfStore({
    storeId,
    pubUserId: userId,
    type,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    saleMode,
    maxiumPurchaseFrequency,
    minimumPurchaseAmount,
    tel,
    // productWithSkus
    activityProductWithSkus,
    // consignment
    consignment,
  });

  ctx.body = {
    ...activity,
  };
});

// 更新门店活动
router.put("/sto/:storeId/activity/:activityId", async (ctx: AppCTX, next) => {
  const { storeId, activityId } = ctx.params;
  const { userId } = ctx;
  const {
    type,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    saleMode,
    minimumPurchaseAmount,
    tel,
    warehouseIds,
    activityProductWithSkus,
  } = ctx.request.body;
  let { consignment, maxiumPurchaseFrequency } = ctx.request.body;

  if (saleMode === ActivitySaleMode.ONLY_STORE_SELLING) {
    consignment = {
      allowHiddenProduct: false,
      allowAllSpokesman: false,
      consignmentBonusSettings: [],
      specificSpokesmanIds: [],
    };
  }

  checkActivityOfStoreParamFields(
    {
      type,
      intro,
      begined,
      ended,
      timeRanges,
      saleMode,
      maxiumPurchaseFrequency,
      warehouseIds,
      activityProductWithSkus,
      consignment,
    },
    false
  );

  if (maxiumPurchaseFrequency === 0) {
    maxiumPurchaseFrequency = undefined;
  }
  let p: UpdateActivityOfStoreParams = {
    type,
    activityId,
    name,
    intro,
    begined,
    ended,
    timeRanges,
    background,
    saleMode,
    maxiumPurchaseFrequency,
    minimumPurchaseAmount,
    tel,
    // productWithSkus
    activityProductWithSkus,
    // consignment
    consignment,
    //
    storeId,
  };

  let activity = await updateActivityOfStore(p);

  ctx.body = {
    ...activity,
  };
});

// 暂停门店活动
router.put(
  "/sto/:storeId/activity/:activityId/pause",
  async (ctx: AppCTX, next) => {
    const { storeId, activityId } = ctx.params;
    const { userId } = ctx;
    const processStatus = await pauseActivityOfStore({ activityId, storeId });
    ctx.body = {
      activityId,
      processStatus,
    };
  }
);

// 恢复门店活动
router.put(
  "/sto/:storeId/activity/:activityId/resume",
  async (ctx: AppCTX, next) => {
    const { storeId, activityId } = ctx.params;
    const { userId } = ctx;
    const processStatus = await resumeActivityOfStore({ activityId, storeId });
    ctx.body = {
      activityId,
      processStatus,
    };
  }
);

// 发布品牌活动
router.put(
  "/sto/:storeId/activity/:activityId/publish",
  async (ctx: AppCTX, next) => {
    const { storeId, activityId } = ctx.params;
    const { userId } = ctx;

    const processStatus = await publishActivityOfStore({
      activityId,
      userId,
      storeId,
    });
    ctx.body = {
      activityId,
      processStatus,
    };
  }
);

export default router;
